﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CLDataAppManagement;
using DataFileApplication_WPF.Extensions;
using DataFileApplication_WPF.Helper;
using DataFileApplication_WPF.Models;
using DataFileApplication_WPF.ViewModels;
using Newtonsoft.Json.Linq;


namespace DataFileApplication_WPF.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    {
        //跟踪当前正在重命名（编辑名称）的树节点，防止多个节点同时进入重命名状态
        private TreeItemStruct currentEditingItem = null;

        public MainView()
        {
            InitializeComponent();
            //设置默认语言
            LanguageManager.CurrentCulture = new CultureInfo("zh-CN");
            // LanguageManager.CurrentCulture = new CultureInfo("en-US");
            MainViewModel ViewModel = new MainViewModel();
            this.DataContext = ViewModel;


            //订阅节点重命名
            if (ViewModel != null && ViewModel.TreeItemInstance != null)
            {
                SubscribeDuplicateNameEvent(ViewModel.TreeItemInstance);
            }

            // 如果 TreeItemInstance 可能会变更，可以监听 PropertyChanged 事件
            if (ViewModel != null)
            {
                ViewModel.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(ViewModel.TreeItemInstance) && ViewModel.TreeItemInstance != null)
                    {
                        SubscribeDuplicateNameEvent(ViewModel.TreeItemInstance);
                    }
                };
            }

        }

        /// <summary>
        /// 订阅重复名称事件
        /// </summary>
        /// <param name="root"></param>
        private void SubscribeDuplicateNameEvent(TreeItemStruct root)
        {
            // 先取消订阅，避免重复
            root.ChildAddDuplicateName -= OnChildAddDuplicateName;
            root.ChildAddDuplicateName += OnChildAddDuplicateName;
            // 递归对子节点也订阅
            foreach (var child in root.Children)
            {
                SubscribeDuplicateNameEvent(child);
            }
        }

        private void OnChildAddDuplicateName(string name)
        {
            // 居中于主窗口
            MessageBox.Show(this, $"节点\"{name}\"已存在！不允许重名！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btn_file_Click(object sender, RoutedEventArgs e)
        {
            if (ExpandedButtonsPanelFile.Visibility == Visibility.Collapsed)
            {
                // 如果隐藏，则设置为可见
                ExpandedButtonsPanelFile.Visibility = Visibility.Visible;
            }
            else
            {
                // 如果可见，则设置为隐藏
                ExpandedButtonsPanelFile.Visibility = Visibility.Collapsed;
            }
        }
        private void btn_language_Click(object sender, RoutedEventArgs e)
        {
            if (ExpandedButtonsPanelLanguge.Visibility == Visibility.Collapsed)
            {
                // 如果隐藏，则设置为可见
                ExpandedButtonsPanelLanguge.Visibility = Visibility.Visible;

            }
            else
            {
                // 如果可见，则设置为隐藏
                ExpandedButtonsPanelLanguge.Visibility = Visibility.Collapsed;
            }
        }

        private void ExpandAll_Click(object sender, RoutedEventArgs e)
        {
            TreeView.ExpandAllNodes();

        }

        private void CollapseAll_Click(object sender, RoutedEventArgs e)
        {
            TreeView.CollapseAllNodes();
        }

        private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (DataContext is MainViewModel viewModel)
            {
                //判断是否为null，如果为null则不进行任何操作（新建文件的时候会触发该事件）
                TreeItemStruct currentSelected = e.NewValue as TreeItemStruct;
                if (currentSelected == null)
                {
                    return;
                }
                viewModel.TreeItemSelected = currentSelected;

                //切换到选中的树节点时，取消当前编辑状态
                if (currentEditingItem != null)
                {
                    currentEditingItem.IsRename = false;
                    currentEditingItem = null;
                }

                //给表格结构赋值
                viewModel.DataGridStructSelected = viewModel.TreeItemSelected.DataGridStructOfTreeItem;
            }
        }

        private void TreeItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (sender is ContentControl && DataContext is MainViewModel viewModel)
            {
                if (currentEditingItem != null)
                {
                    //如果当前有正在编辑的节点，先将其设置为非编辑状态
                    currentEditingItem.IsRename = false;
                }
                viewModel.TreeItemSelected.IsRename = true;
                //将当前选中的树节点设置为正在编辑的节点
                currentEditingItem = viewModel.TreeItemSelected;
            }
        }

        // 文本框失去焦点事件，退出编辑状态
        private void TreeItemRename_LostFocus(object sender, RoutedEventArgs e)
        {
            if (sender is TextBox textBox && DataContext is MainViewModel viewModel)
            {
                viewModel.TreeItemSelected.IsRename = false;
                //当前无编辑节点
                currentEditingItem = null;
            }
        }

        private void TreeItemRename_KeyDown(object sender, KeyEventArgs e)
        {
            if (sender is TextBox textBox && DataContext is MainViewModel viewModel)
            {
                if (e.Key == Key.Enter)
                {
                    // 按下回车键，退出编辑状态
                    viewModel.TreeItemSelected.IsRename = false;

                    //更新名称
                    viewModel.TreeItemSelected.Name = textBox.Text;
                    viewModel.TreeItemSelected.Parent. NamesHashSet.Remove(viewModel.TreeItemSelected.OriginalName);
                    viewModel.TreeItemSelected.Parent. NamesHashSet.Add(viewModel.TreeItemSelected. Name);
                    //当前无编辑节点
                    currentEditingItem = null;
                }
                else if (e.Key == Key.Escape)
                {
                    // 按下 Esc 键，取消编辑，恢复原名称
                    textBox.Text = viewModel.TreeItemSelected.OriginalName;
                    //当前无编辑节点
                    viewModel.TreeItemSelected.IsRename = false;
                    currentEditingItem = null;
                }
            }
        }

        private void RenameItem_Click(object sender, RoutedEventArgs e)
        {
            //if (sender is MenuItem && DataContext is MainViewModel viewModel)
            if ( DataContext is MainViewModel viewModel)
            {
                //当前无编辑节点且当前未选中的节点
                if (currentEditingItem == null && viewModel.TreeItemSelected == null)
                {
                    return;
                }
                else if (currentEditingItem != null)
                {
                    //如果当前有正在编辑的节点，先将其设置为非编辑状态
                    currentEditingItem.IsRename = false;
                    currentEditingItem = null;
                }
                else if (currentEditingItem != null && viewModel.TreeItemSelected == null)
                {
                    return;
                }
                else
                {
                    //编辑状态
                    viewModel.TreeItemSelected.IsRename = true;
                    //将当前选中的树节点设置为正在编辑的节点
                    currentEditingItem = viewModel.TreeItemSelected;
                }
            }
        }

        private void myDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DataContext is MainViewModel viewModel)
            {
                string language = LanguageManager.GetCurrentLanguage();

                DataGridItemStruct dataGridItemStruct = e.AddedItems.Count > 0 ? e.AddedItems[0] as DataGridItemStruct : null;
                var VALUE = dataGridItemStruct?.Clone();
                //单行表格数据
                viewModel.DataGridItemSelectedForEdit = VALUE;

                //var languageCommentsDic = viewModel.DataGridItemSelected?.DataGridComments.LanguageComments.LanguageCommentsDic;

                //if (languageCommentsDic != null && languageCommentsDic.Count != 0)
                //{
                //    viewModel.DataGridItemSelectedLanguage = viewModel.DataGridItemSelected?.DataGridComments.LanguageComments.LanguageCommentsDic[language];

                //}
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 判断是否有未保存的更改（假设ViewModel有IsModified属性）
            var vm = this.DataContext as ViewModels.MainViewModel;

            //迭代时测试
            //  if (vm != null && vm.IsFileModified) // 你需要在ViewModel中实现IsModified属性
            //  {
            var result = MessageBox.Show("文件已修改，是否保存？", "提示", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                // 执行保存命令
                if (vm.SaveFileCommand.CanExecute(null))
                    vm.SaveFileCommand.Execute(null);
            }
            else if (result == MessageBoxResult.No)
            {
                // 直接关闭
            }
            else if (result == MessageBoxResult.Cancel)
            {
                // 取消关闭
                e.Cancel = true;
            }
            //  }
        }

        public static readonly RoutedUICommand RenameCommand = new RoutedUICommand("Rename", "RenameCommand", typeof(MainView));

        private void RenameCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            RenameItem_Click(sender, null);
        }


    }
}
